using System;
using System.Reflection;

namespace SmartPart
{
    public class LateBinder
    {
        /// <exception cref="System.TypeLoadException">The type couldn't be 
        /// loaded.</exception>
        /// <exception cref="System.Exception">The assembly couldn't be loaded 
        /// or other errors.</exception>
        /// <exception cref="System.ArgumentNullException">fullyQualifiedTypeName 
        /// is a null reference.</exception>
        public static object CreateInstance(string assemblyName, string fullyQualifiedTypeName)
        {
            Type type = null;
            if (assemblyName != null)
            {
                // this method will also search the GAC and will use the latest
                // version if multiple versions are found.
                Assembly assembly = Assembly.Load(assemblyName);
                if (assembly != null)
                {
                    type = assembly.GetType(fullyQualifiedTypeName, true, true);
                }
                else
                {
                    throw new Exception("Failed to load assembly \"" + assemblyName + "\".");
                }
            }
            else
            {
                type = Type.GetType(fullyQualifiedTypeName, true, true);
            }
            // invoke the type's constructor to create an instance
            object instance = type.InvokeMember("",
                BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance,
                null,
                null,
                new object[] { });
            return instance;
        }
        public static object CreateInstance(string fullyQualifiedTypeName)
        {
            return CreateInstance(null, fullyQualifiedTypeName);
        }
    }
}

